#!/bin/bash
# Copyright 2025 Supabase, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -uo pipefail

# Get list of proto files to lint
protofiles=$(git diff --cached --name-only --diff-filter=ACM -- '*.proto')
if [ -z "$protofiles" ]; then
  exit 0
fi

# First, try to autofix any issues
# shellcheck disable=SC2086
if go tool protolint -fix $protofiles >/dev/null 2>&1; then
  exit 0
fi

# Run protolint again without -fix to check for remaining issues
# shellcheck disable=SC2086
output=$(go tool protolint $protofiles 2>&1)
exit_code=$?

if [ $exit_code -eq 0 ]; then
  echo "Fixed proto files"
  exit 0
else
  echo "$output"
  exit $exit_code
fi
